package com.chrissy.music.system.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.chrissy.music.common.config.OssConfig;
import com.chrissy.music.common.exception.ApiException;
import com.chrissy.music.system.service.SysFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author Johnson
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SysFileServiceImpl implements SysFileService {

    private final OSS ossClient;

    private final OssConfig ossConfig;
    private static final String FILE_DELIMITER = "/";

    @Override
    public String upload(MultipartFile file) {
        log.info("\n<<------OSS文件上传开始-------->>\n" + file.getOriginalFilename());
        String dir = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        // 判断文件
        String originalFilename = file.getOriginalFilename();
        String cloudFileName = new SimpleDateFormat("HH-mm-ss").format(new Date()) + "-" + UUID.randomUUID() + getExtensionName(originalFilename);
        // 设置上传到云存储的路径
        String cloudPath = dir + FILE_DELIMITER + cloudFileName;
        try {
            // 图片上传
            PutObjectResult result = ossClient.putObject(ossConfig.getBucket(), cloudPath, file.getInputStream());
            if (result != null) {
                log.info("\n<<------OSS文件上传成功------>>\n " + ossConfig.getMarketHost() + "/" + cloudPath);
                return ossConfig.getMarketHost() + "/" + cloudPath;
            }
        } catch (IOException e) {
            log.error("上传失败, 原因为{}", e.getMessage());
            throw new ApiException(500, "上传失败");
        }
        return null;
    }

    /**
     * @param filename 文件名
     * @description 获取文件拓展名
     * @method getExtensionName
     * @author Johnson
     * @date 2022/9/21 21:21
     **/
    private String getExtensionName(String filename) {
        if ((filename == null) || (filename.isEmpty())) {
            return filename;
        }
        int dot = filename.lastIndexOf('.');
        if ((dot > -1) && (dot < (filename.length() - 1))) {
            return filename.substring(dot);
        }
        return filename;
    }
}
